package make

import (
	"fmt"
	"strings"

	"github.com/runningwater/gohub/pkg/console"
	"github.com/spf13/cobra"
)

var CmdMakeAPIController = &cobra.Command{
	Use:   "apicontroller",
	Short: "Create api controller file, example: make apicontroller v1/user",
	Run:   runMakeAPIController,
	Args:  cobra.ExactArgs(1), // 只允许且必须传 1 个参数
}

func runMakeAPIController(cmd *cobra.Command, args []string) {

	// 1. 获取参数，处理参数，要求附带版本号(v1 或 v2)
	array := strings.Split(args[0], "/")
	if len(array) != 2 {
		console.Exit("api controller file format: v1/user")
	}

	// 2. 拼接目标文件路径
	// 如：app/http/controllers/api/v1/user_controller.go
	apiVersion, name := array[0], array[1]
	model := makeModelFromString(name)

	// 3. 拼接目标文件路径
	// 如：app/http/controllers/api/v1/user_controller.go
	filePath := fmt.Sprintf("app/http/controllers/api/%s/%s_controller.go", apiVersion, model.TableName)
	// 4. 基于模板生成文件
	createFileFromTpl(filePath, "apicontroller", model)
}
